/*
 * Copyright (C) 2008 Google Inc.
 * 
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not
 * use this file except in compliance with the License. You may obtain a copy of
 * the License at
 * 
 * http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
 * License for the specific language governing permissions and limitations under
 * the License.
 */

package rowan.application.quickaccess.rss;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;

/**
 * Database for RSS feeds 
 * 
 * Holds multiple tables and can create entries, return all entries 
 * 
 */
public class RssDbAdapter {

    public static final String KEY_TITLE = "title";
    public static final String KEY_BODY = "body";
    public static final String KEY_LINK = "link";
    public static final String KEY_IMAGE = "image";
    public static final String KEY_ROWID = "_id";

    private static final String TAG = "NotesDbAdapter";
    
    private DatabaseHelper mDbHelper;
    private SQLiteDatabase mDb;
    
    public static final String DATABASE_TABLE = "rowan";
    public static final String DATABASE_TABLE_SPORTS ="sports";
    public static final String DATABASE_TABLE_TWITTER = "twitter";
    
    private static final String DATABASE_NAME = "data";
    private static final int DATABASE_VERSION = 2;
    
    /**
     * Database creation sql statement for Rowan Alethics 
     */
    private static final String DATABASE_CREATE_SPORTS =
        "create table sports (_id integer primary key autoincrement, "
        + "title text not null, body text not null, link text not null, image blob not null);";
    
    /**
     * Database creation sql statement for Rowan website
     */
    public static final String DATABASE_CREATE = 
    	"create table rowan (_id integer primary key autoincrement, "
        + "title text not null, body text not null, link text not null);";
   
    /**
     * Database creation sql statement for Rowan twitter
     */
    public static final String DATABASE_CREATE_TWITTER =
    	"create table twitter (_id integer primary key autoincrement, "
        + "title text not null, body text not null, link text not null);";
    
    private final Context mCtx;



    private static class DatabaseHelper extends SQLiteOpenHelper {

        DatabaseHelper(Context context) {
            super(context, DATABASE_NAME, null, DATABASE_VERSION);
        }

        @Override
        public void onCreate(SQLiteDatabase db) {

            db.execSQL(DATABASE_CREATE); // Create Rowan Table
            db.execSQL(DATABASE_CREATE_SPORTS); // Create Sports Table
            db.execSQL(DATABASE_CREATE_TWITTER); // Create Twitter Table
        }

        /**
         * If the table names of the current feeds change, or any part of the Schema, the db version should change
         * if the DB version is changed this method will be called and handle what should happen on upgrades
         */
        @Override
        public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
            Log.w(TAG, "Upgrading database from version " + oldVersion + " to "
                    + newVersion + ", which will destroy all old data");
            db.execSQL("DROP TABLE IF EXISTS rowan");
            db.execSQL("DROP TABLE IF EXISTS sports");
            db.execSQL("DROP TABLE IF EXISTS twitter");
            onCreate(db);
        }
    }

    /**
     * Constructor - takes the context to allow the database to be
     * opened/created
     * 
     * @param ctx the Context within which to work
     */
    public RssDbAdapter(Context ctx) {
        this.mCtx = ctx;
    }

    /**
     * Open the notes database. If it cannot be opened, try to create a new
     * instance of the database. If it cannot be created, throw an exception to
     * signal the failure
     * 
     * @return this (self reference, allowing this to be chained in an
     *         initialization call)
     * @throws SQLException if the database could be neither opened or created
     */
    public RssDbAdapter open() throws SQLException {
        mDbHelper = new DatabaseHelper(mCtx);
        mDb = mDbHelper.getWritableDatabase();
        return this;
    }

    public void close() {
        mDbHelper.close();
    }


    /**
     * 
     * @param title the title of the article
     * @param body the body of the article
     * @param link Link referring to the article
     * @param image Image associated with article if has one
     * @param table The table for the entry to be added to
     * @return rowId or -1 if failed
     */
    public long createEntry(String title, String body, String link, byte[] image, String table) {
    	ContentValues initialValues = new ContentValues();
    	initialValues.put(KEY_TITLE, title);
        initialValues.put(KEY_BODY, body);
        initialValues.put(KEY_LINK, link);
        
        if (table.equals(DATABASE_TABLE_SPORTS)) {
	        initialValues.put(KEY_IMAGE, image);
        }
        
       return mDb.insert(table, null, initialValues);
    }

    /**
     * Delete the note with the given rowId
     * 
     * @param rowId id of note to delete
     * @return true if deleted, false otherwise
     */
    public boolean deleteEntry(long rowId, String table) {

        return mDb.delete(table, KEY_ROWID + "=" + rowId, null) > 0;
    }

    /**
     * Return a Cursor over the list of all notes in the database
     * 
     * @return Cursor over all notes
     */
    public Cursor fetchAllEntries(String table) {
    	if (table.equals(DATABASE_TABLE_SPORTS)){
    		return mDb.query(table, new String[] {KEY_ROWID, KEY_TITLE,
                    KEY_BODY, KEY_LINK, KEY_IMAGE}, null, null, null, null, null);
    	}
        return mDb.query(table, new String[] {KEY_ROWID, KEY_TITLE,
                KEY_BODY, KEY_LINK}, null, null, null, null, null);
    }

    /**
     * Return a Cursor positioned at the note that matches the given rowId
     * 
     * @param rowId id of note to retrieve
     * @return Cursor positioned to matching note, if found
     * @throws SQLException if note could not be found/retrieved
     */
    public Cursor fetchEntry(long rowId, String table) throws SQLException {

        Cursor mCursor =

            mDb.query(true, table, new String[] {KEY_ROWID,
                    KEY_TITLE, KEY_BODY}, KEY_ROWID + "=" + rowId, null,
                    null, null, null, null);
        if (mCursor != null) {
            mCursor.moveToFirst();
        }
        return mCursor;

    }
    
    public boolean clearTable(String table)
    {
    	try{
    		mDb.execSQL("DELETE FROM "+table);
    	}
    	catch (Exception e)
    	{
    		return false;
    	}
    	return true;
    }

}
